package com.jsch.test.poxy;

import java.io.*;
import java.net.Socket;

public class SshdClient {
    private Socket socket;
    private OutputStream out;
    private InputStream in;
    private boolean running = false;

    public void init() throws IOException {
        //创建连接指定Ip和端口的socket
        socket = new Socket("127.0.0.1", 22);
        out = socket.getOutputStream();
        in = socket.getInputStream();
        //创建一个线程用于读取服务器的信息
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    byte[] buf = new byte[10240];
                    running = true;
                    while (running) {
                        int len = 0;
                        while ((len = in.read(buf)) != -1) {
                            System.out.println("sshd响应结果：" + new String(buf, 0, len));
                            proxySdhdResult(buf, len);
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                close();
            }
        }).start();

    }

    /**
     * 发送给sshd服务
     *
     * @param cmd
     */
    public void sendToSshd(byte[] cmd, int len) {
        System.out.println("发送给sshd服务:" + new String(cmd, 0, len));
        while (out == null) {
            System.out.println("等待变量初始化...");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            continue;
        }
        try {
            out.write(cmd, 0, len);
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 代理sshd服务的响应结果
     *
     * @param result
     */
    private void proxySdhdResult(byte[] result, int len) {
        if (sshdListener != null) {
            sshdListener.onSshdResult(result, len);
        }
    }

    private SshdListener sshdListener;

    public void setSshdListener(SshdListener sshdListener) {
        this.sshdListener = sshdListener;
    }

    public void close() {
        running = false;
        try {
            if (out != null) {
                out.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            if (in != null) {
                in.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public interface SshdListener {
        void onSshdResult(byte[] result, int len);
    }
}
